/**
 * 智慧小区管理系统 - 业主管理API接口
 * @author Wu.Liang
 * @date 2025-08-20
 * @updated 2025-08-20 - 创建业主管理API接口，遵循Controller命名规范
 */
import api from './request'
import type { ApiResponse } from './request'

// 业主房户关联数据类型
export interface OwnerHouseholdData {
  id: number
  communityName: string
  buildingName: string
  unitName: string
  roomNumber: string
  ownershipType: number
  ownershipRatio: number
  isPrimaryOwner: boolean
  certificateNumber?: string
  certificateDate?: string
  mortgageInfo?: string
}

// 业主数据类型定义
export interface OwnerData {
  id: number
  ownerName: string
  idCard: string
  phone: string
  email?: string
  gender: number
  birthDate?: string
  address?: string
  occupation?: string
  company?: string
  emergencyContact?: string
  emergencyPhone?: string
  remark?: string
  status: number
  createTime: string
  updateTime: string
  // 扩展字段
  genderDesc?: string
  statusDesc?: string
  householdCount?: number
  // 业主状态：0-未激活，1-已激活，2-已禁用
  ownerStatus?: number
  // 关联状态：0-未关联，1-已关联
  associationStatus?: number
  // 关联状态描述
  associationStatusText?: string
  // 房户关联信息
  households?: OwnerHouseholdData[]
}

// 业主编辑数据类型定义（包含原始数据，不脱敏）
export interface OwnerEditData {
  id: number
  ownerName: string
  idCard: string // 原始身份证号，不脱敏
  phone: string // 原始手机号，不脱敏
  email?: string
  gender: number
  birthDate?: string
  address?: string
  occupation?: string
  company?: string
  emergencyContact?: string
  emergencyPhone?: string // 原始紧急联系电话，不脱敏
  remark?: string
  status: number
  createTime: string
  updateTime: string
  // 扩展字段
  genderDesc?: string
  statusDesc?: string
  // 业主状态：0-未激活，1-已激活，2-已禁用
  ownerStatus?: number
}

// 业主查询条件
export interface OwnerQueryDTO {
  ownerName?: string
  idCard?: string
  phone?: string
  email?: string
  gender?: number
  occupation?: string
  company?: string
  status?: number
  communityId?: number
  buildingId?: number
  unitId?: number
  householdId?: number
  keyword?: string
  startTime?: string
  endTime?: string
  // 关联状态：0-未关联，1-已关联
  associationStatus?: number
  // 分页参数
  current?: number
  size?: number
}

// 业主创建/更新DTO
export interface OwnerDTO {
  ownerName: string
  idCard: string
  phone: string
  email?: string
  gender?: number
  birthDate?: string
  address?: string
  occupation?: string
  company?: string
  emergencyContact?: string
  emergencyPhone?: string
  remark?: string
  status?: number
}

// 业主更新DTO（编辑时使用，身份证号可选）
export interface OwnerUpdateDTO {
  ownerName: string
  phone?: string
  email?: string
  gender?: number
  birthDate?: string
  address?: string
  occupation?: string
  company?: string
  emergencyContact?: string
  emergencyPhone?: string
  remark?: string
  status?: number
}

// 业主房户关联DTO
export interface OwnerWithHouseholdDTO {
  ownerInfo: OwnerDTO
  householdId: number
}

// 分页响应类型
export interface PageResult<T> {
  records: T[]
  total: number
  size: number
  current: number
  pages: number
}

// 业主统计信息
export interface OwnerStatistics {
  totalCount: number
  activeCount: number
  propertyCount: number
  certificateCount: number
}

// 业主房户关联创建/更新DTO
export interface OwnerHouseholdDTO {
  ownerId: number
  householdId: number
  ownershipType: number
  ownershipRatio: number
  ownershipStartDate?: string
  ownershipEndDate?: string
  isPrimaryOwner: boolean
  certificateNumber?: string
  certificateDate?: string
  mortgageInfo?: string
  remark?: string
}

/**
 * 业主管理API接口
 */
export const ownerApi = {
  /**
   * 分页查询业主列表
   * @param params 查询参数
   * @returns 分页结果
   */
  getOwnerPage: (params: OwnerQueryDTO): Promise<ApiResponse<PageResult<OwnerData>>> => {
    return api.get('/api/region/owner/page', { params })
  },

  /**
   * 根据ID查询业主详情
   * @param id 业主ID
   * @returns 业主详情
   */
  getOwnerById: (id: number): Promise<ApiResponse<OwnerData>> => {
    return api.get(`/api/region/owner/${id}`)
  },

  /**
   * 创建业主
   * @param data 业主信息
   * @returns 业主ID
   */
  createOwner: (data: OwnerDTO): Promise<ApiResponse<number>> => {
    return api.post('/api/region/owner', data)
  },

  /**
   * 更新业主
   * @param id 业主ID
   * @param data 业主信息
   * @returns 操作结果
   */
  updateOwner: (id: number, data: OwnerUpdateDTO): Promise<ApiResponse<void>> => {
    return api.put(`/api/region/owner/${id}`, data)
  },

  /**
   * 删除业主
   * @param id 业主ID
   * @returns 操作结果
   */
  deleteOwner: (id: number): Promise<ApiResponse<void>> => {
    return api.delete(`/api/region/owner/${id}`)
  },

  /**
   * 批量删除业主
   * @param ids 业主ID列表
   * @returns 操作结果
   */
  batchDeleteOwners: (ids: number[]): Promise<ApiResponse<void>> => {
    return api.delete('/api/region/owner/batch', { data: ids })
  },

  /**
   * 检查身份证号是否存在
   * @param idCard 身份证号
   * @param excludeId 排除的业主ID（用于编辑时检查）
   * @returns 是否存在
   */
  checkIdCardExists: (idCard: string, excludeId?: number): Promise<ApiResponse<boolean>> => {
    const params: any = { idCard }
    if (excludeId) {
      params.excludeId = excludeId
    }
    return api.get('/api/region/owner/check/idcard', { params })
  },

  /**
   * 检查手机号是否存在
   * @param phone 手机号
   * @param excludeId 排除的业主ID（用于编辑时检查）
   * @returns 是否存在
   */
  checkPhoneExists: (phone: string, excludeId?: number): Promise<ApiResponse<boolean>> => {
    const params: any = { phone }
    if (excludeId) {
      params.excludeId = excludeId
    }
    return api.get('/api/region/owner/check/phone', { params })
  },

  /**
   * 获取业主统计信息
   * @returns 统计信息
   */
  getOwnerStatistics: (): Promise<ApiResponse<OwnerStatistics>> => {
    return api.get('/api/region/owner/statistics')
  },

  /**
   * 获取业主关联的房户列表
   * @param ownerId 业主ID
   * @returns 房户关联列表
   */
  getOwnerHouseholds: (ownerId: number): Promise<ApiResponse<OwnerHouseholdData[]>> => {
    return api.get(`/api/region/owner/${ownerId}/households`)
  },

  /**
   * 创建业主房户关联
   * @param data 关联信息
   * @returns 关联ID
   */
  createOwnerHousehold: (data: OwnerHouseholdDTO): Promise<ApiResponse<number>> => {
    return api.post('/api/region/owner/household', data)
  },

  /**
   * 更新业主房户关联
   * @param id 关联ID
   * @param data 关联信息
   * @returns 操作结果
   */
  updateOwnerHousehold: (id: number, data: OwnerHouseholdDTO): Promise<ApiResponse<void>> => {
    return api.put(`/api/region/owner/household/${id}`, data)
  },

  /**
   * 删除业主房户关联
   * @param id 关联ID
   * @returns 操作结果
   */
  deleteOwnerHousehold: (id: number): Promise<ApiResponse<void>> => {
    return api.delete(`/api/region/owner/household/${id}`)
  },

  /**
   * 设置主业主
   * @param ownerId 业主ID
   * @param householdId 房户ID
   * @returns 操作结果
   */
  setPrimaryOwner: (ownerId: number, householdId: number): Promise<ApiResponse<void>> => {
    return api.put(`/api/region/owner/${ownerId}/household/${householdId}/primary`)
  },

  /**
   * 新增业主并关联房户（完整流程）
   * @param data 业主房户关联信息
   * @returns 操作结果
   */
  addOwnerWithHousehold: (data: OwnerWithHouseholdDTO): Promise<ApiResponse<string>> => {
    return api.post('/api/region/owner/add-with-household', data)
  },

  /**
   * 获取业主列表（包含关联状态）
   * @param params 查询参数
   * @returns 分页结果
   */
  getOwnerListWithAssociation: (params: OwnerQueryDTO): Promise<ApiResponse<PageResult<OwnerData>>> => {
    return api.get('/api/region/owner/list-with-association', { params })
  },

  /**
   * 获取未关联房户的业主列表
   * @param params 查询参数
   * @returns 分页结果
   */
  getUnassociatedOwnerList: (params: OwnerQueryDTO): Promise<ApiResponse<PageResult<OwnerData>>> => {
    return api.get('/api/region/owner/unassociated', { params })
  },

  /**
   * 获取已关联房户的业主列表
   * @param params 查询参数
   * @returns 分页结果
   */
  getAssociatedOwnerList: (params: OwnerQueryDTO): Promise<ApiResponse<PageResult<OwnerData>>> => {
    return api.get('/api/region/owner/associated', { params })
  },

  /**
   * 获取业主编辑数据
   * @param id 业主ID
   * @returns 业主编辑数据
   */
  getOwnerEditData: (id: number): Promise<ApiResponse<OwnerEditData>> => {
    return api.get(`/api/region/owner/edit/${id}`)
  }
}

export default ownerApi
